from rest_framework.views import APIView
from rest_framework.permissions import IsAdminUser
from users.models import User
from rest_framework.response import Response
from datetime import date,timedelta
from rest_framework.generics import ListAPIView
from . import home_serializers
from goods.models import CategoryVisitCount

#1,获取用户总数
class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self,request):

        #1,获取用户总数
        # count = User.objects.filter(is_staff=False).count()
        count = User.objects.count()

        #2,返回响应
        return Response({
            "count":count
        })

#2,获取日增用户
class UserDayIncreaseCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        #1,查询日增用户数量
        count = User.objects.filter(date_joined__gte=date.today()).count()

        #2,返回响应
        return Response({
            "count":count
        })

#3,获取日活用户
class UserDayActiveCountView(APIView):
    def get(self,request):

        #1,查询日活用户数量
        count = User.objects.filter(last_login__gte=date.today()).count()

        #2,返回响应
        return Response({
            "count":count
        })

#4,获取日下单用户
class UserDayOrdersCountView(APIView):
    def get(self,request):
        #1,查询日下单用户
        count = User.objects.filter(orderinfo__create_time__gte=date.today()).count()

        #2,返回响应
        return Response({
            "count":count
        })

#5,获取月增用户
class UserMonthIncrementCountView(APIView):
    def get(self,request):

        #1,获取30天前的时间
        old_date = date.today() - timedelta(days=30)

        #2,遍历30天,查询每天的新增用户
        count_list = []
        for i in range(1,31):

            #2,1获取当天时间
            current_date = old_date + timedelta(days=i)

            #2,2获取下一天时间
            next_date = old_date + timedelta(days=i+1)

            #2,3查询用户
            count = User.objects.filter(date_joined__gte=current_date,date_joined__lt=next_date).count()

            #2,4添加到列表中
            count_list.append({
                "count":count,
                "date":current_date
            })

        #3,返回响应
        return Response(count_list)

#6,获取商品分类访问量
class GoodCategoryVisitCountView(ListAPIView):
    # queryset = CategoryVisitCount.objects.all()
    serializer_class = home_serializers.GoodCategorySerializer

    def get_queryset(self):
        return CategoryVisitCount.objects.filter(date=date.today()).all()

    # def get(self,request):

        #方式1
        #1,获取查询集
        # categories = self.get_queryset()
        #
        # #2,创建序列化器对象
        # serializer = self.get_serializer(instance=categories,many=True)
        #
        # #4,返回响应
        # return Response(serializer.data)

        #方式2
        # return self.list(request)
